package com.op.teachingliteapp.fragment;

import android.graphics.Canvas;
import org.vudroid.core.codec.CodecContext;
import org.vudroid.core.codec.CodecDocument;
import org.vudroid.core.codec.CodecPage;
import org.vudroid.pdfdroid.codec.PdfContext;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.LruCache;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.op.teachingliteapp.R;
import com.op.teachingliteapp.sender.Runtime;
import com.op.teachingliteapp.sender.listener.onDrawListener;
import com.op.teachingliteapp.sender.ui.view.DrawingWithBezier;
import com.op.teachingliteapp.util.ScreenSendUtils;


public class PPTShowFragment extends Fragment {
    private Button penBtn;
    private int pageCount;
    private CodecContext pdf_conext;
    private DrawingWithBezier pptView;
    private CodecDocument pdf_documen;
    private int index;
    private LruCache<Integer, Bitmap> bitmapLruCache;
    private GestureDetector gestureDetector;
    public static boolean isScroll = true;
    private int width;
    private int height;
    private Activity activity;
    private PopupWindow popWindow;
    private RadioGroup radioGroup;//颜色
    private RadioGroup moderadioGroup;//选择画笔大小
    private Button clearScreen;//清除屏幕的按钮
    private Button goBackMovePdf;//从画笔回到pdf的画面移动

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        /*
		 * 只是new一次popWindow
		 * 同时修正之前画笔要画第二次才能显示的问题了 kim zhang
		 */
    	final View root = inflater.inflate(R.layout.fragment_ppt_show, container, false);
        this.activity = getActivity();
        LayoutInflater lif = (LayoutInflater) getActivity().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View poPlayOut = lif.inflate(R.layout.set_pen, null);
        this.radioGroup = (RadioGroup) poPlayOut.findViewById(R.id.pen_color);
        this.moderadioGroup = (RadioGroup) poPlayOut.findViewById(R.id.pen_mode);
        this.clearScreen = (Button) poPlayOut.findViewById(R.id.cleer);
        this.goBackMovePdf=(Button) poPlayOut.findViewById(R.id.hand1);
        this.popWindow = new PopupWindow(poPlayOut, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        this.popWindow.setBackgroundDrawable(new BitmapDrawable());//这个不能删
        this.popWindow.setFocusable(false);//修正
        this.popWindow.setOutsideTouchable(true);
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowMgr = (WindowManager) this.activity.getSystemService(Context.WINDOW_SERVICE);
        windowMgr.getDefaultDisplay().getMetrics(dm);
        this.width = dm.widthPixels;
        this.height = dm.heightPixels;

        pptView = (DrawingWithBezier) root.findViewById(R.id.pptView);
        pptView.setOnDrawListener(new onDrawListener() {
            @Override
            public void drawEnd(Canvas canvas) {
                if (Runtime.isSend()) {
                    new Thread(new send(pptView)).start();
                }

                //new Thread(new SenderRunnable(Runtime.ip, Constants.teacherPort, pptView)).start();

            }
        });
		/*
		 * 画笔按钮选择
		 * kim zhang by 2015.6.29
		 * 修正了清除画笔的点击问题
		 */
        penBtn = (Button) root.findViewById(R.id.pen);
        penBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
            	penBtn.setBackgroundResource(R.drawable.huabi2);
                isScroll = false;
                popWindow.showAtLocation(getView(), Gravity.BOTTOM,(width/2)-520, 0);//x,y, y正数向上
                // popWindow.showAsDropDown(root.findViewById(R.id.pen), 0, 0);//显示位置
                //从画笔回到pdf的画面移动
                goBackMovePdf.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						penBtn.setBackgroundResource(R.drawable.hand2);
						isScroll = true;//true是回到从画笔回到pdf的画面移动
					}
				} );
                //清屏按钮监听
                clearScreen.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                    	isScroll = false;
                        pptView.reset();
                        pptView.invalidate();
//                        isScroll = false;
//                        pptView.reset();
//                        pptView.invalidate();
                        
                    }
                });
                //画笔大小监听
                moderadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        switch (checkedId) {
                            case R.id.big:
                                DrawingWithBezier.setmodeMUN(21);
                                break;
                            case R.id.middle:
                                DrawingWithBezier.setmodeMUN(13);
                                break;
                            case R.id.small:
                                DrawingWithBezier.setmodeMUN(7);
                                break;
                            default:
                                break;
                        }
                    }
                });
                //画笔颜色大小监听
                radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        isScroll = false;
                        switch (checkedId) {
                            case R.id.green:
                                DrawingWithBezier.setmGesturePaintColor(R.id.green);
                                break;
                            case R.id.red:
                                DrawingWithBezier.setmGesturePaintColor(R.id.red);
                                break;
                            case R.id.black:
                                DrawingWithBezier.setmGesturePaintColor(R.id.black);
                                break;
                            case R.id.blue:
                                DrawingWithBezier.setmGesturePaintColor(R.id.blue);
                                break;

                            default:
                        }
                    }

                });
            }
        });


        gestureDetector = new GestureDetector(getActivity(), new GestureListener());
        pptView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isScroll) {
                    return gestureDetector.onTouchEvent(event);
                } else {
                    return false;
                }

            }
        });


        pdf_conext = new PdfContext();
        String url = getArguments().getString("url");
        Log.i("PPTShowFragment", "--------" + url + "----------");
        pdf_documen = pdf_conext.openDocument(url);
        this.pageCount = pdf_documen.getPageCount();
        index = 0;

        changePage(index);


        return root;
    }


    @Override
    public void onDestroyView() {
        //        new Thread(new SenderRunnable(Runtime.ip, Constants.teacherPort, null)).start();
        super.onDestroyView();
    }

    private void changePage(int i) {

        if (i < 0) {
            this.index = 0;
            Toast.makeText(getActivity(), "已经到达第一页", Toast.LENGTH_LONG).show();
            return;
        } else if (i > pageCount - 1) {
            this.index = pageCount - 1;
            Toast.makeText(getActivity(), "已经到底最后一页", Toast.LENGTH_LONG).show();
            return;

        }
        CodecPage pdf_page = pdf_documen.getPage(i);
        RectF rf = new RectF();
        rf.bottom = rf.right = (float) 1.0;
        //		int w = pdf_page.getWidth();
        //		int h = pdf_page.getHeight();
        Bitmap bitmap = pdf_page.renderBitmap(this.width, this.height, rf);
        //        pptView.invalidate();
        pptView.reset();
        pptView.setBitmap(bitmap);
        pptView.invalidate();
//        Runtime.view = pptView;
        new Thread(new send(pptView)).start();


    }

    private class GestureListener extends GestureDetector.SimpleOnGestureListener {


        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            Log.i("onFling", "onFling");
            if (e1.getX() - e2.getX() > 50) {
                changePage(++index);
                Log.i("onFling", String.valueOf(index));
            } else if (e2.getX() - e1.getX() > 50) {

                changePage(--index);
                Log.i("onFling", String.valueOf(index));
            }
            return true;
        }
    }

    class send implements Runnable {
        private View view;

        public send(View view) {
            this.view = view;

        }

        @Override
        public void run() {
//            if (Runtime.isSend) {
//                ScreenSendUtils.send(Runtime.context, this.view);
//            }

        }

    }
}

